package com.cictec.middleware.gps.engine.event.listener;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.core.entity.Device;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.BusInstanceEngine;
import com.cictec.middleware.gps.engine.TimeEventBus;
import com.cictec.middleware.gps.engine.event.DeviceOnlineEvent;
import com.cictec.middleware.gps.engine.send.SendHandler;
import com.cictec.middleware.gps.engine.service.DataStorageToRedisService;
import com.cictec.middleware.gps.service.DeviceService;
import com.google.common.eventbus.Subscribe;


/**
 * 设备上下线 事件处理监听【中间件外部事件】
 * @author Administrator
 *
 */
@Component
public class DeviceOnlineOfflineListener {
	
	private static Logger logger = LoggerFactory.getLogger(DeviceOnlineOfflineListener.class);
	
	@Autowired
	private TimeEventBus timeEventBus;
	
	@Autowired
	private BusInstanceEngine busInstanceEngine;
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private DataStorageToRedisService dataStorageToRedisService;
	
	@PostConstruct
	public void init() {
		logger.debug("注册【DeviceOnlineOfflineListener】到TimeEventBus， 监听器：DeviceOnlineOfflineListener ---> 事件：DeviceOnlineEvent");
		timeEventBus.register(this);

	}
	
	/**
	 * 更新 设备在线、离线状态
	 * @param event
	 */
	@Subscribe
	public void onHandler(DeviceOnlineEvent event){
		logger.debug(" 设备在线、离线状态 发生变化，更新数据库；重新发布车辆位置信息");
		
		BusInstance  busInstance = busInstanceEngine.getBusInstanceByDevCode(event.getDevCode());
		
		Device device  = busInstance.getDevice();
		deviceService.updateDeviceOnlineStatusByDevUuid(device.getDevUuid(), event.getDevOnline());
		
		/** 重新推送某个车辆的位置信息 */
		if(busInstance.getAttributes().size() > 5){ // 有数据
			SendHandler.sendBusPostionToMq(busInstance);		// 推送至 mq
			SendHandler.sendBusPostionToStomp(busInstance);		// 推送至 apollo
			
			if(!busInstance.isDevOnline()){
				dataStorageToRedisService.saveBusOfflinePositation(busInstance);
			}else{
				dataStorageToRedisService.deleteBusOfflinePositation(busInstance);
			}
		}
	}
	

}
